//
//  AddressManagerViewController.m
//  ChunLaiZhuangClient
//
//  Created by zzs on 16/3/9.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "AddressManagerViewController.h"
#import "AddressManagerTableViewCell.h"
#import "ReceiptAddressEditViewController.h"
#import "AddressListModel.h"
#import "AddressEmptyView.h"
#import "ReceiptAddressEditViewController.h"
#import "AddressListModel.h"
#import "CLZRefreshHeader.h"
@interface AddressManagerViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addressArray;
@property (nonatomic, strong) AddressEmptyView *emptyView;
@property (nonatomic, strong) NSIndexPath *indexPath;
@end


@implementation AddressManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNaviTitle:@"收货地址管理"];
    [self setNaviLeftButton];
    [self.addressArray addObject:[[NSObject alloc] init]];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.emptyView.hidden = YES;
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [CLZRefreshHeader headerWithRefreshingBlock:^{
        [weakSelf getAddressList];
    }];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getAddressList];
}

- (AddressEmptyView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[AddressEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width)];
        __weak typeof(self) weakSelf = self;
        _emptyView.AddNewAddressBlock = ^(){
            ReceiptAddressEditViewController *editAddressVC = [[ReceiptAddressEditViewController alloc] init];
            [weakSelf.navigationController pushViewController:editAddressVC animated:YES];
        };
        [self.view addSubview:_emptyView];
        [_emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(@(10));
            make.size.mas_equalTo(CGSizeMake(300, 300));
        }];
    }
    return _emptyView;
}

- (void)getAddressList {
    [[LKDHud shareHud] showLoadingView];
    __weak typeof(self) weakSelf = self;
    [ApiClient getAddressListDidFinishLoaded:^(AddressListModel *model, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        [self.tableView.mj_header endRefreshing];
        if ([model.status isEqual:@(1)]) {
            if(model.data.addresses.count > 0) {
                weakSelf.emptyView.hidden = YES;
                weakSelf.addressArray = [NSMutableArray arrayWithArray: model.data.addresses];
                [weakSelf.addressArray addObject:[[AddressSubModel alloc] init]];
                [weakSelf.tableView reloadData];
            } else {
                self.emptyView.hidden = NO;
            }
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < (self.addressArray.count - 1)) {
        AddressManagerTableViewCell *cell = (AddressManagerTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        return [cell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height + 1;
    } else {
        return 50.f;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.row < (self.addressArray.count - 1)) {
        AddressSubModel *model = [self.addressArray objectAtIndex:indexPath.row];
        static NSString *identifier = @"AddressManagerTableViewCell";
        cell = [tableView dequeueReusableCellWithIdentifier:
                identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddressManagerTableViewCell" owner:nil options:nil] lastObject];
        }
        [((AddressManagerTableViewCell *)cell) updateAddressInfo:model];
        ((AddressManagerTableViewCell *)cell).setDefaultAddressAction = ^(){
            [ApiClient setDefaultAddress:model.address_id didFinishLoaded:^(KXJson *json, NSString *path) {
                NSString *status = [json getStringForKey:@"status"];
                if ([status isEqualToString:@"1"]) {
                    [[LKDHud shareHud]showtip:@"设置默认地址成功"];
                    model.is_default = YES;
                    for (AddressSubModel *amodel in self.addressArray) {
                        if (amodel != model) {
                            amodel.is_default = NO;
                        }
                    }
                }
            } didFailLoaded:^(NSError *error, NSString *path) {
                
            }];
        };
        __weak typeof(self) weakSelf = self;
        ((AddressManagerTableViewCell *)cell).deleteAddressAction = ^(){
            [weakSelf deleteCommodityOfIndex:indexPath];
        };
    } else {
        static NSString *identifier = @"ReceiptAddressFootCell";
        cell = [tableView dequeueReusableCellWithIdentifier:
                identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ReceiptAddressFootTableViewCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row < self.addressArray.count - 1) {
        AddressSubModel *model = [self.addressArray objectAtIndex:indexPath.row];
        ReceiptAddressEditViewController *editAddressVC = [[ReceiptAddressEditViewController alloc] initWithAddressInfo:model];
        [self.navigationController pushViewController:editAddressVC animated:YES];
    } else {
        ReceiptAddressEditViewController *editAddressVC = [[ReceiptAddressEditViewController alloc] init];
        [self.navigationController pushViewController:editAddressVC animated:YES];
    }
}

- (void)deleteCommodityOfIndex:(NSIndexPath *)index {
    self.indexPath = index;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确定要删除吗？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        AddressSubModel *model = [self.addressArray objectAtIndex:self.indexPath.row];
        __weak typeof(self) weakSelf = self;
        [ApiClient deleteAddress:model.address_id didFinishLoaded:^(KXJson *json, NSString *path) {
            NSString *status = [json getStringForKey:@"status"];
            if ([status isEqualToString:@"1"]) {
                [weakSelf.addressArray removeObject:model];
                if (weakSelf.addressArray.count == 1) {
                    [weakSelf.addressArray removeLastObject];
                    weakSelf.emptyView.hidden = NO;
                    [weakSelf.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:self.indexPath, [NSIndexPath indexPathForRow:1 inSection:0], nil] withRowAnimation:UITableViewRowAnimationTop];
                } else {
                    [weakSelf.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:self.indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
                }
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
